// ResponsiveFileItem 完整实现
// 为了保持代码清晰，将主要方法实现分离到这个文件

#include "responsivefileitem.h"
#include <QApplication>
#include <QPainter>
#include <QDebug>

using namespace SonyIveDesign;

// === 布局度量更新实现 ===
void ResponsiveFileItem::LayoutMetrics::updateForMode(DisplayMode mode)
{
    switch (mode) {
        case DisplayMode::Micro:
            iconSize = DesignConstants::ICON_SIZE_SMALL;
            padding = DesignConstants::SPACING_MICRO;
            spacing = DesignConstants::SPACING_MICRO;
            borderRadius = 4;
            primaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, true);
            secondaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, false);
            break;

        case DisplayMode::Compact:
            iconSize = DesignConstants::ICON_SIZE_SMALL;
            padding = DesignConstants::SPACING_SMALL;
            spacing = DesignConstants::SPACING_SMALL;
            borderRadius = 6;
            primaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, true);
            secondaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, false);
            break;

        case DisplayMode::Standard:
            iconSize = DesignConstants::ICON_SIZE_MEDIUM;
            padding = DesignConstants::SPACING_NORMAL;
            spacing = DesignConstants::SPACING_NORMAL;
            borderRadius = DesignConstants::BORDER_RADIUS;
            primaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, true);
            secondaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, false);
            break;

        case DisplayMode::Expanded:
            iconSize = DesignConstants::ICON_SIZE_LARGE;
            padding = DesignConstants::SPACING_LARGE;
            spacing = DesignConstants::SPACING_NORMAL;
            borderRadius = DesignConstants::BORDER_RADIUS;
            primaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, true);
            secondaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, false);
            break;

        case DisplayMode::Full:
            iconSize = DesignConstants::ICON_SIZE_LARGE;
            padding = DesignConstants::SPACING_LARGE;
            spacing = DesignConstants::SPACING_LARGE;
            borderRadius = DesignConstants::BORDER_RADIUS + 2;
            primaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, true);
            secondaryFont = AdaptiveTextProcessor::getAdaptiveFont(mode, false);
            break;
    }
}

// === 主要接口实现 ===

void ResponsiveFileItem::setFileInfo(const UnifiedFileInfo& fileInfo)
{
    if (m_fileInfo.fileIdentity != fileInfo.fileIdentity) {
        m_fileInfo = fileInfo;
        m_backgroundCacheDirty = true;
        m_sizeHintCached = false;
        m_layoutMetricsCached = false;

        if (!m_backgroundCacheTimer->isActive()) {
            m_backgroundCacheTimer->start();
        }

        update();
    }
}

void ResponsiveFileItem::setDisplayMode(DisplayMode mode)
{
    if (m_displayMode != mode) {
        DisplayMode oldMode = m_displayMode;
        m_displayMode = mode;
        m_layoutMetricsCached = false;
        m_backgroundCacheDirty = true;
        m_sizeHintCached = false;


        animateModeTransition();
        emit displayModeChanged(mode);
    }
}

void ResponsiveFileItem::setSelected(bool selected)
{
    if (m_isSelected != selected) {
        m_isSelected = selected;
        animateSelection(selected);

        if (m_engine) {
            m_engine->animateSelectionEffect(this, selected);
        }

    }
}

void ResponsiveFileItem::setHovered(bool hovered)
{
    if (m_isHovered != hovered) {
        m_isHovered = hovered;
        animateHover(hovered);

        if (m_engine) {
            m_engine->animateHoverEffect(this, hovered);
        }

        if (hovered && shouldUseComplexEffects()) {
            updateDropShadow();
        }
    }
}

void ResponsiveFileItem::setPressed(bool pressed)
{
    if (m_isPressed != pressed) {
        m_isPressed = pressed;
        m_backgroundCacheDirty = true;
        update();
    }
}

void ResponsiveFileItem::setResponsiveEngine(ResponsiveFileListEngine* engine)
{
    if (m_engine != engine) {
        m_engine = engine;

        if (m_engine) {
            // 同步当前显示模式
            DisplayMode currentMode = m_engine->getCurrentDisplayMode();
            if (currentMode != m_displayMode) {
                setDisplayMode(currentMode);
            }
        }

    }
}

// === 动画属性实现 ===

void ResponsiveFileItem::setAnimationOpacity(double opacity)
{
    if (qAbs(m_animationOpacity - opacity) > 0.01) {
        m_animationOpacity = qBound(0.0, opacity, 1.0);
        update();
    }
}

void ResponsiveFileItem::setHoverScale(double scale)
{
    if (qAbs(m_hoverScale - scale) > 0.01) {
        m_hoverScale = qBound(0.8, scale, 1.2);
        update();
    }
}

void ResponsiveFileItem::setSelectionScale(double scale)
{
    if (qAbs(m_selectionScale - scale) > 0.01) {
        m_selectionScale = qBound(0.9, scale, 1.1);
        update();
    }
}

// === QWidget接口实现 ===

QSize ResponsiveFileItem::sizeHint() const
{
    if (!m_sizeHintCached) {
        if (m_engine) {
            m_cachedSizeHint = m_engine->calculateItemSize(m_displayMode);
        } else {
            // 后备计算
            switch (m_displayMode) {
                case DisplayMode::Micro:    m_cachedSizeHint = QSize(140, 32); break;
                case DisplayMode::Compact:  m_cachedSizeHint = QSize(200, 40); break;
                case DisplayMode::Standard: m_cachedSizeHint = QSize(280, 48); break;
                case DisplayMode::Expanded: m_cachedSizeHint = QSize(380, 56); break;
                case DisplayMode::Full:     m_cachedSizeHint = QSize(480, 64); break;
            }
        }
        m_sizeHintCached = true;
    }

    return m_cachedSizeHint;
}

QSize ResponsiveFileItem::minimumSizeHint() const
{
    return QSize(120, 28); // Micro模式的最小尺寸
}

// === 绘制方法实现 ===

void ResponsiveFileItem::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);

    // 应用动画变换
    if (shouldUseComplexEffects()) {
        painter.setOpacity(m_animationOpacity);

        if (m_hoverScale != 1.0 || m_selectionScale != 1.0) {
            double totalScale = m_hoverScale * m_selectionScale;
            QRect rect = this->rect();
            painter.translate(rect.center());
            painter.scale(totalScale, totalScale);
            painter.translate(-rect.center());
        }
    }

    // Sony风格分层绘制
    drawSonyBackground(painter);
    drawAdaptiveIcon(painter);
    drawAdaptiveText(painter);

    // 根据显示模式绘制额外元素
    if (m_displayMode >= DisplayMode::Compact) {
        drawStatusBadge(painter);
    }

    if (m_displayMode >= DisplayMode::Standard) {
        drawProgressIndicator(painter);
    }

    if (m_displayMode >= DisplayMode::Expanded) {
        drawLayoutModeIndicator(painter);
    }

    // 选择状态覆盖层
    if (m_isSelected) {
        drawSelectionOverlay(painter);
    }
}

// === 鼠标事件处理 ===

void ResponsiveFileItem::mousePressEvent(QMouseEvent* event)
{
    if (!event) return;

    if (event->button() == Qt::LeftButton) {
        m_dragStartPos = event->pos();
        m_isDragStarted = false;
        m_pressModifiers = QApplication::keyboardModifiers();
        setPressed(true);
    } else if (event->button() == Qt::RightButton) {
        emit rightClicked(this, event->globalPosition().toPoint());
    }

    QWidget::mousePressEvent(event);
}

void ResponsiveFileItem::mouseReleaseEvent(QMouseEvent* event)
{
    if (!event) return;

    if (event->button() == Qt::LeftButton) {
        setPressed(false);

        if (!m_isDragStarted) {
            emit clicked(this, m_pressModifiers);
        }

        m_isDragStarted = false;
        m_pressModifiers = Qt::NoModifier;
    }

    QWidget::mouseReleaseEvent(event);
}

void ResponsiveFileItem::mouseDoubleClickEvent(QMouseEvent* event)
{
    if (!event) return;

    if (event->button() == Qt::LeftButton) {
        emit doubleClicked(this);
    }

    QWidget::mouseDoubleClickEvent(event);
}

void ResponsiveFileItem::mouseMoveEvent(QMouseEvent* event)
{
    if (!event) return;

    if (event->buttons() & Qt::LeftButton && !m_isDragStarted) {
        int distance = (event->pos() - m_dragStartPos).manhattanLength();
        if (distance >= QApplication::startDragDistance()) {
            m_isDragStarted = true;
            emit dragStartRequested(this, m_dragStartPos);
        }
    }

    QWidget::mouseMoveEvent(event);
}

void ResponsiveFileItem::enterEvent(QEnterEvent* event)
{
    Q_UNUSED(event)
    setHovered(true);
    QWidget::enterEvent(event);
}

void ResponsiveFileItem::leaveEvent(QEvent* event)
{
    Q_UNUSED(event)
    setHovered(false);
    QWidget::leaveEvent(event);
}

void ResponsiveFileItem::resizeEvent(QResizeEvent* event)
{
    // 尺寸变化时检查是否需要更新显示模式
    if (m_engine) {
        DisplayMode newMode = m_engine->calculateDisplayMode(event->size().width());
        if (newMode != m_displayMode) {
            setDisplayMode(newMode);
        }
    }

    m_backgroundCacheDirty = true;
    m_layoutMetricsCached = false;

    QWidget::resizeEvent(event);
}

// === 槽函数实现 ===

void ResponsiveFileItem::onHoverAnimationFinished()
{
}

void ResponsiveFileItem::onSelectionAnimationFinished()
{
}

void ResponsiveFileItem::onBackgroundCacheUpdate()
{
    if (m_backgroundCacheDirty) {
        updateBackgroundCache();
    }
}

// === ResponsiveFileItemFactory 实现 ===

ResponsiveFileItem* ResponsiveFileItemFactory::createItem(const UnifiedFileInfo& fileInfo,
                                                         ResponsiveFileListEngine* engine,
                                                         DisplayMode mode,
                                                         QWidget* parent)
{
    auto* item = new ResponsiveFileItem(fileInfo, engine, parent);
    item->setDisplayMode(mode);
    applyDefaultSettings(item);

    return item;
}

void ResponsiveFileItemFactory::configureForPerformance(ResponsiveFileItem* item, bool enablePerformanceMode)
{
    if (item) {
        item->enablePerformanceMode(enablePerformanceMode);
    }
}

void ResponsiveFileItemFactory::applyTheme(ResponsiveFileItem* item, const QString& themeName)
{
    Q_UNUSED(item)
    Q_UNUSED(themeName)
    // TODO: 实现主题应用逻辑
}

QList<ResponsiveFileItem*> ResponsiveFileItemFactory::createBatch(const QList<UnifiedFileInfo>& fileInfos,
                                                                 ResponsiveFileListEngine* engine,
                                                                 QWidget* parent)
{
    QList<ResponsiveFileItem*> items;
    items.reserve(fileInfos.size());

    for (const auto& fileInfo : fileInfos) {
        items.append(createItem(fileInfo, engine, DisplayMode::Standard, parent));
    }

    return items;
}

void ResponsiveFileItemFactory::applyDefaultSettings(ResponsiveFileItem* item)
{
    if (item) {
        // 应用默认设置
        item->setAnimationOpacity(1.0);
        item->setHoverScale(1.0);
        item->setSelectionScale(1.0);
    }
}